package org.dromara.oce.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bytedance.ads.model.ToolsWechatAppletCreateV30Response;
import com.bytedance.ads.model.ToolsWechatAppletListV30ResponseData;
import com.bytedance.ads.model.ToolsWechatAppletListV30ResponseDataListInner;
import com.bytedance.ads.model.ToolsWechatAppletUpdateV30ResponseData;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.oce.domain.OceMicroWechatApp;
import org.dromara.oce.domain.bo.OceMicroWechatAppBo;
import org.dromara.oce.domain.qo.GetToolsWechatAppletListQo;
import org.dromara.oce.domain.qo.OceMicroWechatAppQo;
import org.dromara.oce.domain.req.CreateToolsWechatAppletReq;
import org.dromara.oce.domain.req.UpdateToolsWechatAppletReq;
import org.dromara.oce.domain.vo.OceMicroWechatAppVo;
import org.dromara.oce.mapper.OceMicroWechatAppMapper;
import org.dromara.oce.service.OceMicroWechatAppService;
import org.dromara.oce.service.remote.OceanEngineThirdRemoteService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 微信小程序Service业务层处理
 *
 * @author dsbb
 * @date 2025-06-04
 */
@RequiredArgsConstructor
@Service
public class OceMicroWechatAppServiceImpl extends ServiceImpl<OceMicroWechatAppMapper,OceMicroWechatApp> implements OceMicroWechatAppService {

    private final OceMicroWechatAppMapper baseMapper;

    private final OceanEngineThirdRemoteService oceanEngineThirdRemoteService;

    /**
     * 查询微信小程序
     *
     * @param instanceId 主键
     * @return 微信小程序
     */
    @Override
    public OceMicroWechatAppVo queryById(Long instanceId){
        return baseMapper.selectVoById(instanceId);
    }

    /**
     * 分页查询微信小程序列表
     *
     * @param qo        查询条件
     * @param pageQuery 分页参数
     * @return 微信小程序分页列表
     */
    @Override
    public TableDataInfo<OceMicroWechatAppVo> queryPageList(OceMicroWechatAppQo qo, PageQuery pageQuery) {
        LambdaQueryWrapper<OceMicroWechatApp> lqw = buildQueryWrapper(qo);
        Page<OceMicroWechatAppVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的微信小程序列表
     *
     * @param qo 查询条件
     * @return 微信小程序列表
     */
    @Override
    public List<OceMicroWechatAppVo> queryList(OceMicroWechatAppQo qo) {
        LambdaQueryWrapper<OceMicroWechatApp> lqw = buildQueryWrapper(qo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OceMicroWechatApp> buildQueryWrapper(OceMicroWechatAppQo qo) {
        LambdaQueryWrapper<OceMicroWechatApp> lqw = Wrappers.lambdaQuery();
        lqw.eq(qo.getAccountId() != null, OceMicroWechatApp::getAccountId, qo.getAccountId());
        lqw.eq(qo.getAdvertiserId() != null, OceMicroWechatApp::getAdvertiserId, qo.getAdvertiserId());
        lqw.eq(StringUtils.isNotBlank(qo.getAppId()), OceMicroWechatApp::getAppId, qo.getAppId());
        lqw.like(StringUtils.isNotBlank(qo.getAppName()), OceMicroWechatApp::getAppName, qo.getAppName());
        lqw.like(StringUtils.isNotBlank(qo.getUserName()), OceMicroWechatApp::getUserName, qo.getUserName());
        lqw.eq(StringUtils.isNotBlank(qo.getAuditStatus()), OceMicroWechatApp::getAuditStatus, qo.getAuditStatus());
        lqw.like(!ObjectUtils.isEmpty(qo.getRemarkMessage()),OceMicroWechatApp::getRemarkMessage,qo.getRemarkMessage());
        return lqw;
    }

    /**
     * 新增微信小程序
     *
     * @param bo 微信小程序
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(OceMicroWechatAppBo bo) {
        OceMicroWechatApp add = MapstructUtils.convert(bo, OceMicroWechatApp.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setInstanceId(add.getInstanceId());
        }
        return flag;
    }

    /**
     * 修改微信小程序
     *
     * @param bo 微信小程序
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(OceMicroWechatAppBo bo) {
        OceMicroWechatApp update = MapstructUtils.convert(bo, OceMicroWechatApp.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OceMicroWechatApp entity){
    }

    /**
     * 校验并批量删除微信小程序信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public boolean createToolsWechatApplet(Long accountId, CreateToolsWechatAppletReq req) {
        ToolsWechatAppletCreateV30Response response = oceanEngineThirdRemoteService.createToolsWechatAppletResponse(accountId, req);
        if (response.getCode() != 0) {
            throw new ServiceException("创建微信小程序失败," + response.getMessage());
        }
        OceMicroWechatApp add = new OceMicroWechatApp();
        BeanUtil.copyProperties(req,add);
        add.setAppName(req.getName());
        add.setInstanceId(response.getData().getData().getInstanceId());

        GetToolsWechatAppletListQo wechatQo = new GetToolsWechatAppletListQo();
        wechatQo.setAccountId(accountId);
        wechatQo.setAdvertiserId(req.getAdvertiserId());
        ToolsWechatAppletListV30ResponseData responseList = oceanEngineThirdRemoteService.getToolsWechatAppletList(wechatQo);
        List<ToolsWechatAppletListV30ResponseDataListInner> list = responseList.getList();
        List<ToolsWechatAppletListV30ResponseDataListInner> result = list.stream().filter(obj -> obj.getInstanceId().equals( add.getInstanceId())).collect(Collectors.toList());
        if (!result.isEmpty() && result.size() > 0){
            ToolsWechatAppletListV30ResponseDataListInner data = result.get(0);
            add.setAuditStatus(data.getAuditStatus().getValue());
            String jsonString = data.getTagInfo();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode rootNode = objectMapper.readTree(jsonString);
                StringBuilder stringBuilder = new StringBuilder();
                OceMicroAppServiceImpl.extractCategoryNames(rootNode, stringBuilder);
                add.setTagInfoDesc(stringBuilder.toString());
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        boolean flag = baseMapper.insert(add) > 0;
        return flag;
    }

    @Override
    public boolean updateToolsWechatApplet(Long accountId, UpdateToolsWechatAppletReq req) {
        ToolsWechatAppletUpdateV30ResponseData response = oceanEngineThirdRemoteService.updateToolsWechatApplet(accountId, req);
        OceMicroWechatApp update = baseMapper.selectById(response.getData().getInstanceId());
        if(update == null){
            throw new ServiceException("系统暂无此小程序");
        }
        BeanUtil.copyProperties(req,update);

        GetToolsWechatAppletListQo wechatQo = new GetToolsWechatAppletListQo();
        wechatQo.setAccountId(accountId);
        wechatQo.setAdvertiserId(req.getAdvertiserId());
        ToolsWechatAppletListV30ResponseData responseList = oceanEngineThirdRemoteService.getToolsWechatAppletList(wechatQo);
        List<ToolsWechatAppletListV30ResponseDataListInner> list = responseList.getList();
        List<ToolsWechatAppletListV30ResponseDataListInner> result = list.stream().filter(obj -> obj.getInstanceId().equals( update.getInstanceId())).collect(Collectors.toList());
        if (!result.isEmpty() && result.size() > 0){
            ToolsWechatAppletListV30ResponseDataListInner data = result.get(0);
            update.setAppName(data.getName());
            update.setAuditStatus(data.getAuditStatus().getValue());
            String jsonString = data.getTagInfo();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode rootNode = objectMapper.readTree(jsonString);
                StringBuilder stringBuilder = new StringBuilder();
                OceMicroAppServiceImpl.extractCategoryNames(rootNode, stringBuilder);
                update.setTagInfoDesc(stringBuilder.toString());
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        boolean flag = baseMapper.updateById(update) > 0;
        return flag;
    }
}
